import os
import datetime
from threading import Thread
from core.wchat.models import WxUserInfo
from core.wchat.wx_base import WxBase
from finance_c2c.local_settings import Config
from core.tools.edit_photo import EditPicture


def make_qr_img(salesman, short=False):
    wx_base = WxBase()
    now_time = datetime.datetime.now()
    content = Config.sales_id + "%s" % salesman.id
    file_bytes_io = wx_base.get_qr_file(content, short=short)
    # 保存二维码文件
    file_name = "%s.jpg" % salesman.id
    file_path = EditPicture.save_file(file_bytes_io, file_name, relation_path="qr_scene")
    # 修改图片大小
    out = EditPicture.resize_img(file_path, box=(408, 408))
    out.save(file_path)
    path = file_path.split("/finance_c2c")[1]
    salesman.scene_qr_code = path
    if short:
        print("short, true", short)
        salesman.expire_time = now_time + datetime.timedelta(days=29)
    else:
        print("short, False", short)
        salesman.expire_time = now_time + datetime.timedelta(days=365 * 100)
    salesman.save()
    return file_path


def make_ad(salesman, valid_status=True):
    """
    制作广告图
    :return:

    """
    wx_base = WxBase()
    if valid_status:
        file_path = os.path.join(Config.base_dir, salesman.scene_qr_code[1:])
    else:
        file_path = make_qr_img(salesman, short=False)
    # 贴二维码
    background_path = os.path.join(Config.base_dir, "c2c_media/ad_background.jpg")
    paste_qr_path = os.path.join(Config.base_dir, "c2c_media/qr_scene/%s_paste_qr.jpg" % salesman.id)
    EditPicture.past_img(background_path, file_path, paste_qr_path, box=(682, 3005))
    # 写文字
    finished_path = os.path.join(Config.base_dir, "c2c_media/qr_scene/%s_finished.jpg" % salesman.id)
    font_file = os.path.join(Config.base_dir, "core/font_file/msyh.ttc")
    expire_time = salesman.expire_time.strftime("%m月%d日")
    words = [{"font_file": font_file, "font_size": 64, "box": (1484, 3252), "words": salesman.tel,
              "color": (255, 255, 255)},
             {"font_file": font_file, "font_size": 30, "box": (840, 3449), "words": expire_time,
              "color": (255, 255, 255)},
             ]
    EditPicture.write_words(paste_qr_path, words, save_pth=finished_path)
    # 上传素材文件
    res = wx_base.upload_file("image", finished_path)
    media_id = res.get("media_id")
    # 发送给用户
    wx_base.send_image(salesman.wx_user.openid, res.get("media_id"))
    return media_id, finished_path, file_path

# def guiguangtu(openid):
#     user_info = WxUserInfo.objects.get(openid=openid)
#     salesman = user_info.salesman
#     now_time = datetime.datetime.now()
#     if salesman.expire_time and salesman.expire_time > now_time:
#         # 有有效的二维码
#         if salesman.adv_expire_time and salesman.adv_expire_time == salesman.expire_time:
#             # 有广告图并且二维码没过期
#             wx_base = WxBase()
#             if salesman.adv_img_media_expire_time >= now_time:
#                 # 直接发送
#                 wx_base.send_image(openid, salesman.adv_img_media_id)
#             else:
#                 res = wx_base.upload_file("image", salesman.adv_img)
#                 media_id = res.get("media_id")
#                 wx_base.send_image(salesman.wx_user.openid, media_id)
#         else:
#             # 根据有效的二维码生成广告图
#             media_id, adv_img, file_path = make_ad(salesman)
#             salesman.adv_img = adv_img
#             salesman.adv_expire_time = salesman.expire_time
#             salesman.adv_img_media_id = media_id
#             salesman.adv_img_media_expire_time = now_time + datetime.timedelta(days=2)
#             salesman.save()
#     else:
#         # 如果没有生成过微信的二维码
#         media_id, finished_path, file_path = make_ad(salesman, valid_status=False)
#         path = file_path.split("/finance_c2c")[1]
#         salesman.scene_qr_code = path
#         salesman.adv_img = finished_path
#         salesman.expire_time = now_time + datetime.timedelta(days=29)
#         salesman.adv_expire_time = salesman.expire_time
#         salesman.adv_img_media_id = media_id
#         salesman.adv_img_media_expire_time = now_time + datetime.timedelta(days=2)
#         salesman.save()


# def make_tg_img(openid):
#     wx_base = WxBase()
#     wx_user_info = WxUserInfo.objects.filter(openid=openid)
#     if wx_user_info.exists():
#         try:
#             sales_man = wx_user_info[0].salesman
#             if sales_man.qr_code:
#                 Thread(target=guiguangtu, args=(openid,)).start()
#             else:
#                 content = '小主：请先在“我的”中完善个人资料，上传微信二维码。'
#                 Thread(target=wx_base.send_text, args=(openid, content)).start()
#         except Exception as e:
#             print(e)
#             content = '小主：请先确认是否已完成注册。'
#             Thread(target=wx_base.send_text, args=(openid, content)).start()
#     else:
#         content = '小主：请先确认是否已完成注册。'
#         Thread(target=wx_base.send_text, args=(openid, content)).start()
